from django.core.files.storage import Storage
from django.conf import settings
from django.utils.deconstruct import deconstructible
from fdfs_client.client import Fdfs_client


# 装饰器的作用:在迁移的是够字段能够被序列化
@deconstructible
class FileStorage(Storage):
    """
    自定义存储类
    1.定义类继承 Storage
    2.重写init方法,保证变量能被初始化
    3.重写open,save,exists,url
    """
    def __init__(self, base_url=None):
        if not base_url:
            base_url = settings.BASE_URL
        self.base_url = base_url

    def open(self, name, mode='rb'):
        """
        打开文件
        :param name:
        :param mode:
        :return:
        """
        pass

    def save(self, name, content, max_length=None):
        """
        保存文件
        :param name: 文件名字
        :param content: 文件内容
        :param max_length: 最大上传量
        :return:
        """
        # 1.创建对象
        client = Fdfs_client('utils/fdfs/client.conf')
        # 2.上传
        result = client.upload_by_buffer(content.read())
        print(result)
        # 3.判断是否上传成功
        if result['Status'] == 'Upload successed.':
            print(result['Remote file_id'])
            return result['Remote file_id']

        else:
            raise Exception('图片上传失败')

    def exists(self, name):
        return False

    def url(self, name):

        return self.base_url + name

